'use strict'

const {
  Pay,
  Order,
  utils,
  log,
  config
} = require('cm')

const db = uniCloud.database()

// 获取通知结果
const output = (provider) => {
  let result
  switch (provider) {
    case 'wx':
      result = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'
      break
    default:
      result = {}
  }
  log.log('\n' + result, '返回给平台方的结果')
  return result
}

exports.main = async (event, context) => {
  log.log(event.path, '请求地址')
  const path = event.path.substring(1)
  const pathArr = path.split('_')
  const options = {
    provider: pathArr[0],
    appType: pathArr[1]
  }
  
  try {
    let pay = new Pay(options)
    const verifyRes = await pay.verifyNotify(event)
    log.log(verifyRes, '平台方通知订单支付结果')
    
    let res
    if (verifyRes) {
      let {
        outTradeNo,
        totalFee,
        transactionId,
        resultCode
      } = verifyRes
      
      let order = await Order.getOrder({
        _id: outTradeNo
      })
      if (totalFee === order.data.price && (resultCode === 'SUCCESS' || resultCode === 'FINISHED')) {
        await order.update({
          // 记录下支付平台的订单号
          'payOptions.platformId': transactionId,
          // 改变支付状态
          state: 'success'
        })
        log.log('校验成功', '校验结果')
      }
      else {
        await order.update({
          // 记录下支付平台的订单号
          'payOptions.platformId': transactionId,
          // 改变支付状态
          state: 'failed'
        })
        log.log('校验信息不匹配', '校验结果')
      }      
    }
    else {
      log.log('未获取到校验信息', '校验结果')
    }
    
    return output(options.provider)
  }
  catch (e) {
    log.error(e)
    log.log('校验过程出现错误', '校验结果')
    return output(options.provider)
  }
}
